import axios from 'axios'
import store from '@/store'
import router from '@/router'
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // 设置axios请求的基础的基础地址
  // baseURL: 'http://ihrm-java.itheima.net' // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
  // baseURL: 'http://localhost:3000'
  baseURL: '/api'
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // console.log(token)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器   对每次返回的数据进行脱壳处理
service.interceptors.response.use(response => {
  // console.log(response.data)
  // 判断 success的结果是false 还是true
  if (response.data.success) {
    // 如果是true那么 返回脱壳之后的数据
    return response.data
  } else {
    // 如果是false 返回message的错误信息
    return Promise.reject(new Error(response.data.message))
  }
}, async error => {
  if (error.response.data.code === 10002) {
    console.log('token失效')
    await store.dispatch('user/logout')
    router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
  }
  return Promise.reject(error)
})

export default service

